<template>

    <div class="design-media">
        <MaterialsEmbroideryUpload v-model="upload_dialog" ref="uploader" type="card" />

        <UxDialog :visible="visible" @close="close()">
            <div class="media-dialog">

                <!-- 初始化加载中 -->
                <UxLoading2 class="init-loading" v-if="!inited" :loading="true" />

                <!-- 全局为空 -->
                <DesignerEmbDstSelectEmpty v-else-if="empty" @doUpload="doUpload($event)" />

                <template v-else>

                    <DesignerMediaForm name="Embroidery File" :form="form" @search="getSearching($event)"
                                       @doUpload="doUpload($event)" />

                    <!-- 滚动区 -->
                    <div class="scroller" ref="scroller" @scroll="onScroll($event)" :offset="top > 1 ? 'scroll' : ''">

                        <!-- 未登录 -->
                        <div class="uploaded-list" v-if="!isLogin">
                            <MaterialsEmbroideryList :list="uploaded" @select="setSelect($event)" :platen="platen" />
                        </div>

                        <!-- 搜索 -->
                        <div class="searching-list" v-else-if="form.name">
                            <div class="search-match">
                                <strong v-text="form.total"></strong>
                                <em v-if="form.total > 1"> matches found</em>
                                <em v-else> match found</em>
                            </div>
                            <UxSearchEmpty v-if="list.length == 0" />
                            <MaterialsEmbroideryList v-else :list="list" @select="setSelect($event)" :platen="platen" />
                        </div>

                        <!-- 外层管理 -->
                        <div class="manage-list" v-else>
                            <!-- 最近使用 -->
                            <div class="manage-list-recently" v-if="recentlyUpload.length > 0">
                                <h3>Recently used</h3>
                                <MaterialsEmbroideryList :list="recentlyUpload" @select="setSelect($event)"
                                                         :platen="platen" />
                            </div>

                            <!-- 图片列表 -->
                            <div class="manage-list-files" v-if="list.length > 0">
                                <h3>My files</h3>
                                <MaterialsEmbroideryList :list="list" @select="setSelect($event)" :platen="platen" />
                            </div>
                        </div>

                        <div class="load-more" v-show="list.length > 0" :status="form.status">
                            <span v-if="form.status == 'loading'">-- Scroll to bottom load data --</span>
                            <span v-if="form.status == 'waiting'">-- Loading --</span>
                            <span v-if="form.status == 'nomore'"></span>
                        </div>

                    </div>

                    <UxLoading2 :loading="loading" />

                </template>

            </div>

        </UxDialog>

        <UxDialog :visible="large" @close="large = false">

            <div class="emb-dst-large">
                <figure><img src="@/assets/images/designer/designer-emb-large.png" alt=""></figure>
                <p>Design size is too large for the embroidery frame.</p>
                <button type="primary" @click="large = false">OK</button>
            </div>
        </UxDialog>
    </div>

</template>

<script>
import { mapGetters } from "vuex";
export default {
    props: {
        recentlyUpload: { type: Array, default: () => [] },
    },
    data () {
        return {
            inited: false,
            visible: false,
            loading: false,
            callback: null,
            platen: null,
            // recently: [], // 最近使用
            uploaded: [], // 上传中的（未登录状态下才有）
            form: { name: '', page: 1, size: 10, status: 'waiting', total: 0, },
            list: [], // 未归类的，搜索的，目录内的
            top: 0,
            large: false,
            upload_dialog: false,
        };
    },

    computed: {
        ...mapGetters({
            isLogin: "getIsLogin",
        }),
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),
        empty () {
            if (!this.isLogin) {
                // 未登录
                return this.uploaded.length == 0
            } else if (this.form.name) {
                // 搜索或是路径中
                return false;
            } else {
                return this.uploaded.length == 0 && this.list.length == 0 && this.recentlyUpload.length == 0
            }

        },
    },
    methods: {

        // 获取用户图片
        async getResourceList (option = {}) {

            const request = {
                search_name: typeof option.name != 'undefined' ? option.name : this.form.name,
                page_num: typeof option.page != 'undefined' ? option.page : this.form.page,
                page_size: typeof option.size != 'undefined' ? option.size : this.form.size,
            };

            const response = await this.$http("Material.getEmbList", request);
            const list = (response.data || []).map(item => {
                item.type = '';
                item.file = null;
                item.image = null;
                item.percent = 0;
                item.error = '';
                return item;
            })

            // 清空数据
            if (request.page_num == 1) {
                this.list.splice(0, this.list.length);
                this.list = list;

            } else {
                this.list.push(...list)
            }

            this.form.total = response.total || 0;
            this.form.status = list.length < this.form.size ? "nomore" : "waiting";
        },


        // 是否不能选中
        isDisabled (width, height) {
            if (!this.platen) {
                return false;
            } else {
                // 比较最长边
                const size = {
                    width: this.platen.width * 254 / 300,
                    height: this.platen.height * 254 / 300,
                }
                const max = Math.max(size.width, size.height) > Math.max(width, height)
                const min = Math.min(size.width, size.height) > Math.min(width, height)
                return !(max && min)
            }
        },


        // 滚动事件
        onScroll (event) {

            const scroller = this.$refs.scroller
            if (!scroller) {
                // 没有滚动
            } else {
                this.top = scroller.scrollTop || 0;

                if (this.isLogin && this.form.status == "waiting") {

                    const offset = 10;
                    const inner = scroller.scrollHeight || 0
                    const outer = scroller.clientHeight || 0

                    if (inner - outer - this.top < offset) {
                        this.form.status = "loading";
                        this.form.page += 1;
                        this.getResourceList();
                    }
                }
            }
        },

        // 搜索功能
        getSearching (keywords) {
            const request = {
                name: keywords,
                page: 1,
            }
            this.loading = true;
            this.getResourceList(request).then(res => {
                this.loading = false
                this.form.name = request.name;
                this.form.page = request.page;
                this.$refs.scroller && (this.$refs.scroller.scrollTop = 0)
            });
        },

        // 选中文件上传
        doUpload () {
            this.$refs.uploader && this.$refs.uploader.startUpload(dst => {
                if (dst) {
                    // const item = {
                    //     id: dst.id,
                    //     file_name: dst.file_name,
                    //     file_type: dst.file_type,
                    //     width: dst.width,
                    //     height: dst.height,
                    //     line_color: dst.line_color,
                    //     stitches: dst.stitches,
                    //     stitches_count: dst.stitches_count,
                    // };


                    if (this.isLogin) {
                        this.getResourceList({ page: 1 })
                    } else {
                        this.uploaded.unshift({ ...dst });// 未登录
                    }

                    // 如果上传的图片
                    if (this.isDisabled(dst.width, dst.height)) {
                        // 上传的过大
                        this.large = true;
                    } else {
                        this.$emit("global:DESIGN_OPEN_EMB_DST_EDIT_DIALOG", {
                            stitches: dst.stitches,
                            stitches_count: dst.stitches_count,
                            line_color: dst.line_color,
                            dst_name: dst.file_name,
                            dst_width: dst.width,
                            dst_height: dst.height,
                            type: 'upload',
                            callback: (res) => {
                                const insert = { ...dst, line_color: res.line_color }
                                this.setSelect(insert);
                            }
                        });

                    }

                } else {
                    this.$uxMessage.warning('Upload failed!');
                }
            })
        },

        // 选中图片
        setSelect (dst) {
            // 已登录的，有两种情况，1.选择素材文件，2.上传文件
            let option = {
                id: dst.id,
                file_name: dst.file_name,
                width: dst.width,
                height: dst.height,
                line_color: dst.line_color,
                stitches: dst.stitches,
                stitches_count: dst.stitches_count,
            };


            // 更新最近使用
            // this.recently = this.recently.filter((item) => item.id != dst.id);
            // this.recently.unshift({ ...dst });
            // this.recently.splice(5, Math.max(this.recently.length - 5, 0));

            this.callback && this.callback(option)
            this.close();
        },

        open (option) {
            // 取用户数据
            this.visible = true;
            this.callback = option.callback
            this.platen = option.platen

            if (!this.inited) {
                this.getResourceList().then((res) => {
                    this.inited = true;
                })
            }
        },
        loadAfterLogin () {
            this.inited && this.getResourceList()
        },
        // 关闭弹窗
        close () {
            this.uploading = null;
            this.visible = false;
        },
    },

    created () {
        this.$on("global:DESIGN_OPEN_EMB_TXT_SELECT_DIALOG", (option) => this.open(option));
        this.$on("global:DESIGN_MEDIA_LOGIN", () => this.loadAfterLogin());
    },
};
</script>

<style lang="scss" scoped>
.media-dialog {
    box-sizing: border-box;
    width: calc(100vw - 80px);
    height: calc(100vh - 80px);
    max-width: 1116px;
    max-height: 800px;
    display: flex;
    flex-direction: column;
    background: #f8f8f8;
    border-radius: 12px;

    &>.loading {
        border-radius: 12px;

        &.init-loading {
            background: none;
        }
    }

    .scroller {
        flex: 1;
        overflow: auto;
        position: relative;
        padding: 0 18px 0;
        border-top: 1px solid transparent;

        &[offset='scroll'] {
            border-top-color: #e6e6e6;
        }
    }

    .image-list {
        margin-top: 18px;

        &::v-deep figure {
            &>span {
                width: 100%;
                height: 100%;
                left: 0;
                top: 0;
                right: 0;
                bottom: 0;
                opacity: 0;
            }

            &:hover>span {
                opacity: 0;
            }
        }

        &::v-deep .image-list-unedited {
            display: none;
        }
    }

    .load-more {
        height: 50px;
        line-height: 50px;
        text-align: center;

        &[status='nomore'] {
            height: 18px;
        }
    }
}

.uploaded-list {}

.searching-list {
    min-height: 100%;
    display: flex;
    flex-direction: column;

    .search-match {
        padding: 20px 0 0;
        font-size: 18px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 18px;

        strong {
            font-weight: 500;
        }
    }

    .media-image-list {
        margin-top: 18px;
    }

    .search-empty {
        margin-top: 18px;
        margin-bottom: 18px;
        flex: 1;
    }
}

.manage-list {
    h3 {
        font-size: 18px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 18px;
    }

    .manage-list-folders,
    .manage-list-files {
        margin-top: 32px;
    }
}

.emb-dst-large {
    width: 320px;
    height: 414px;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-sizing: border-box;
    padding: 54px 14px 14px;

    figure {
        width: 80px;
        height: 80px;

        img {
            width: 100%;
            height: 100%;
        }
    }

    p {
        flex: 1;
        display: flex;
        align-items: center;
        justify-items: center;
        font-family: Roboto, Roboto;
        font-weight: 400;
        font-size: 16px;
        color: #000000;
        line-height: 22px;
        text-align: center;
        margin-bottom: 52px;
    }

    button {
        width: 100%;
    }
}
</style>
